//
//  ByDocumentaryUserVC.m
//  caipiao_ios
//
//  Created by mc on 2018/8/10.
//  Copyright © 2018年 ZhangZhanbin. All rights reserved.
//

#import "ByDocumentaryUserVC.h"
#import "ByDocumentaryUserTitleCell.h"
#import "ByDocumentaryUserListCell.h"
#import "ByDocumentaryControlView.h"
#import "ByDocumentCell.h"
#import "ByDocumentaryUserHeadView.h"
#import "ByCoreViewSegmentControl.h"
#import "ByDocumentaryDetailVC.h"
#import "ByDocumentaryBombView.h"

@interface ByDocumentaryUserVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ByCoreViewSegmentControl *segTitle;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) ByDocumentaryUserHeadView *headView;

@property (nonatomic, strong) ByNetModel *detailModel;
@property (nonatomic, strong) UILabel *recordLabel;

@property (nonatomic, strong) ByDocumentaryBombView *handleBombView;

@property (nonatomic, strong) ByNetModel *orderModel;

@property (nonatomic, strong) ByPayBombView *payBombView;

@property (nonatomic, strong) ByNetModel *orderModel1;


@end

@implementation ByDocumentaryUserVC

- (ByDocumentaryBombView *)handleBombView{
    if (_handleBombView == nil) {
        _handleBombView = [[ByDocumentaryBombView alloc] init];
        
        __weak typeof(self) weakSelf = self;
        __weak typeof(ByDocumentaryBombView *) weakSelfView = _handleBombView;
        _handleBombView.updateBlock = ^(){
            weakSelfView.totalLabel.text = [NSString stringWithFormat:@"共%ld元",self.orderModel.single_amount.integerValue * weakSelfView.addMinusView.countLabel.text.integerValue];
        };
        _handleBombView.moneyLabel.text = [NSString stringWithFormat:@"最低跟单金额:%@元",weakSelf.orderModel.low_amount];
        _handleBombView.totalLabel.text = [NSString stringWithFormat:@"共%ld元",weakSelf.orderModel.single_amount.integerValue * 5];
        
        _handleBombView.betBlock = ^(){

            if (weakSelf.orderModel.low_amount.integerValue > weakSelf.orderModel.single_amount.integerValue * weakSelfView.addMinusView.countLabel.text.integerValue) {
                [ByCoreToolAlert showOnlyText:@"跟单金额小于最低跟单金额"];
                [weakSelf.handleBombView remove];
                weakSelf.handleBombView = nil;
                return;
                
            }
            [ByCoreToolAlert showLoadind:@"处理中" hasMasker:YES];
            ByNetModel *netModel = [[ByNetModel alloc] init];
            netModel.plan_id = weakSelf.orderModel.ID;
            netModel.num = weakSelfView.addMinusView.countLabel.text;
            [ByDocumentaryApi followOrderFollowPlan:netModel success:^(ByNetBaseResult *result) {
                [ByCoreToolAlert hideHud];
                [weakSelf.handleBombView remove];
                weakSelf.handleBombView = nil;
                weakSelf.orderModel1 = [[ByNetModel alloc] initContentWithDic:result.data[@"data"]];
                weakSelf.payBombView.moneyLabel.text = [NSString stringWithFormat:@"%@元", weakSelf.orderModel1.amount];
                weakSelf.payBombView.orderModel = weakSelf.orderModel1;
                [weakSelf.payBombView show];
                
            } failure:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showFailureWithText:result.msg];
                [weakSelf.handleBombView remove];
                weakSelf.handleBombView = nil;
            }];
            
        };
    }
    return _handleBombView;
}



- (ByPayBombView *)payBombView{
    if (_payBombView == nil) {
        _payBombView = [[ByPayBombView alloc] init];
        
        __weak typeof(self) weakSelf = self;
        _payBombView.sureBlock = ^(){
            [weakSelf.payBombView remove];
            weakSelf.payBombView = nil;
            [weakSelf loadData];
        };
        
        _payBombView.otherSureBlock = ^(NSString *str,NSInteger type){
            
            [weakSelf.payBombView remove];
            weakSelf.payBombView = nil;
            
            if (type == 1) {
                ByWebViewController *vc = [[ByWebViewController alloc] initWithTotalUrlString:str];
                vc.titleString = @"支付宝支付";
                [weakSelf by_normalPush:vc hasNavi:YES];
            }else{
                ByWechatPayQrView *vc = [[ByWechatPayQrView alloc] init];
                vc.title = @"微信支付";
                vc.str = str;
                [weakSelf by_normalPush:vc hasNavi:YES];
            }
            
        };
        
        _payBombView.otherSureBlock = ^(NSString *str,NSInteger type){
            
            [weakSelf.payBombView remove];
            weakSelf.payBombView = nil;
            
            if (type == 1) {
                ByWebViewController *vc = [[ByWebViewController alloc] initWithTotalUrlString:str];
                vc.titleString = @"支付宝支付";
                [weakSelf by_normalPush:vc hasNavi:YES];
            }else{
                ByWechatPayQrView *vc = [[ByWechatPayQrView alloc] init];
                vc.title = @"微信支付";
                vc.str = str;
                [weakSelf by_normalPush:vc hasNavi:YES];
            }
            
        };
        _payBombView.selectBlock = ^(NSInteger index){
            [ByCoreToolAlert showOnlyText:[NSString stringWithFormat:@"%ld", index]];
        };
    }
    return _payBombView;
}



- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addLeftBackBarButtonItem];
    self.type = 1;
    [self initViews];
    [self loadData];
    
    ByCoreRefreshGifHeader *header = [ByCoreRefreshGifHeader headerWithRefreshingBlock:^{
        [self loadData];
    }];
    self.tableView.mj_header = header;
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:NO];
}

- (void)loadData{
  
    ByNetModel *netModel = [[ByNetModel alloc] init];
    netModel.type = self.type;
    netModel.uid = self.netModel.uid;
   
    [ByCoreToolAlert showLoadind:@"加载中"];
    [ByDocumentaryApi followOrderGodIndex:netModel success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert hideHud];
        [self.tableView.mj_header endRefreshing];
        SLog(@"大神首页 = %@", result.data);
        NSDictionary *dictionary = result.data[@"data"];
        
        self.detailModel = [[ByNetModel alloc] initContentWithDic:dictionary];
        NSDictionary *userInfoDic = dictionary[@"u_info"];
        self.detailModel.nickname = userInfoDic[@"nickname"];
        self.detailModel.head_pic = userInfoDic[@"head_pic"];
        self.detailModel.uid = netModel.uid;
        
       
        
        
        NSDictionary *red_people_numDic = dictionary[@"red_people_num"];
        if ([red_people_numDic isKindOfClass:[NSDictionary class]] && [[red_people_numDic allKeys] count] > 0) {
            
            self.detailModel.red_num = red_people_numDic[@"red_num"];
            self.detailModel.win_amount = red_people_numDic[@"win_amount"];
        }else{
            self.detailModel.red_num = @"0";
            self.detailModel.win_amount = @"0";
        }

        self.headView.netModel = self.detailModel;
        self.recordLabel.text = self.detailModel.all_plan_hit_num;
    
        
        [self.dataArray removeAllObjects];
        
        for (NSDictionary *dic in dictionary[@"plan_info"]) {
            ByNetModel *netModel = [[ByNetModel alloc] initContentWithDic:dic];
            
            if (netModel.origin_num.length > 0) {
                if (netModel.lottery_type.integerValue == 1) {
                    netModel.planDic = [ByFootBallHandle getFootBallGameResultWithPlan:netModel.origin_num];
                }else{
                    netModel.planDic = [ByBasketBallHandle getBasketBallGameResultWithPlan:netModel.origin_num];
                }
            }
            
            NSMutableArray *ball_infoArray = [NSMutableArray arrayWithCapacity:1];
            for (NSDictionary *ball_infoDic in dic[@"ball_info"]) {
                ByNetModel *model = [[ByNetModel alloc] initContentWithDic:ball_infoDic];
                model.planDic = netModel.planDic;
                model.public_type = netModel.public_type;
                model.is_result = netModel.is_result;
                if (netModel.lottery_type.integerValue == 2) {
                    NSDictionary *basketball_infoDic = ball_infoDic[@"basketball_info"];
                    model.game_Result = [ByBasketBallHandle getDocumentaryBasketBallResultWithDic:basketball_infoDic];
                }
                [ball_infoArray addObject:model];
            }
            netModel.ball_infoArray = [ball_infoArray copy];
            
            [self.dataArray addObject:netModel];
        }
         [self.tableView reloadData];
    } failure:^(ByNetBaseResult *result) {
         [self.dataArray removeAllObjects];
         [self.tableView.mj_header endRefreshing];
         [ByCoreToolAlert showFailureWithText:result.msg];
        [self.tableView reloadData];
    }];
                    
    
}

- (void)initViews{
    
    self.view.backgroundColor = BY_BACKGROUND_COLOR;
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = BY_BACKGROUND_COLOR;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.top.equalTo(self.view).offset(0);
        
        if (@available(ios 11.0,*)) {
           make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(0);
        } else {
            make.bottom.equalTo(self.view).offset(0);
        }
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    ByDocumentaryUserHeadView *headView = [[ByDocumentaryUserHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 250)];
    self.tableView.tableHeaderView = headView;
    self.headView = headView;
    headView.updateBlock = ^(){
        [self loadData];
    };
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ByDocumentCell *cell = [ByDocumentCell cellWithTableView:tableView];
    ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.row];
    cell.isUser = YES;
    cell.netModel = netModel;
    cell.betBlock = ^(){
        
        if (BY_USER && [BY_USER.uid isEqualToString:netModel.user_id]) {
            [ByCoreToolAlert showOnlyText:@"用户自己发的跟单，不能跟"];
            return ;
        }
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a= [dat timeIntervalSince1970];
        
        if (a < netModel.end_time.integerValue && netModel.is_result.integerValue == 0){
            
            self.orderModel = [netModel copy];
            [self.handleBombView show];
            
        }else{
            
            [ByCoreToolAlert showOnlyText:@"该跟单方案已截止，无法跟单"];
        }
    };
    return cell;
}





- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.row];
    if (netModel.public_type.integerValue == 2 || (netModel.public_type.integerValue == 1 && netModel.is_result.integerValue == 1)) {
        CGFloat height = netModel.ball_infoArray.count * 35 + 75 + 35;
        return 12 + 75 + 50 + height + 53;
    }else{
        CGFloat height = 35 + 75 + 35;
        return 12 + 75 + 50 + height + 53;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 140)];
        header.backgroundColor = BY_BACKGROUND_COLOR;
        
        UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(5, 2, SCREEN_WIDTH- 10, 90)];
        [header addSubview:backgroundView];
        backgroundView.backgroundColor = [UIColor whiteColor];
        backgroundView.layer.cornerRadius = 5;
        
        
        UIImageView *stateView = [[UIImageView alloc] init];
        [backgroundView addSubview:stateView];
        [stateView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(backgroundView).offset(15);
            make.top.equalTo(backgroundView).offset(15);
            make.size.mas_offset(CGSizeMake(30, 15));
        }];
        stateView.image = [UIImage imageNamed:@"zhuangtai状态"];
        
        ByDottedLineView *line = [[ByDottedLineView alloc] init];
        line.direction = DottedLineViewDirectionHorizontalFromRight;
        line.lineColor = BY_LINE_COLOR;
        line.lengthPattern = @[@4, @3];
        [backgroundView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(backgroundView).offset(0);
            make.right.equalTo(backgroundView).offset(0);
            make.centerY.equalTo(backgroundView).offset(0);
            make.height.mas_equalTo(@1);
        }];
        
        
        UIImageView *recordView = [[UIImageView alloc] init];
        [backgroundView addSubview:recordView];
        [recordView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(backgroundView).offset(15);
            make.bottom.equalTo(backgroundView).offset(-15);
            make.size.mas_offset(CGSizeMake(60, 15));
        }];
        recordView.image = [UIImage imageNamed:@"hongdanjilu红单记录"];
        
        UILabel *recordLabel = [[UILabel alloc] init];
        [backgroundView addSubview:recordLabel];
        [recordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(recordView.mas_right).offset(15);
            make.bottom.equalTo(backgroundView).offset(-10);
            make.size.mas_offset(CGSizeMake(65, 25));
        }];
        recordLabel.backgroundColor = rgba(248, 202, 188, 1);
        recordLabel.textColor = BY_THEME_COLOR;
        recordLabel.text = self.detailModel.all_plan_hit_num;
        recordLabel.textAlignment = NSTextAlignmentCenter;
        recordLabel.font = FONT(12);
        self.recordLabel = recordLabel;
        
        CGFloat magin = 35;
        NSArray *dataArray = self.detailModel.five_game_hit;
        for (int i = 0; i < dataArray.count; i++) {
            NSString *valueString = dataArray[i];
            UIImageView *imageView = [[UIImageView alloc] init];
            [backgroundView addSubview:imageView];
            
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(stateView.mas_right).offset(19 + (24 + magin) * i);
                make.centerY.equalTo(stateView.mas_centerY).offset(0);
                make.size.mas_equalTo(CGSizeMake(24, 24));
            }];
            if (valueString.integerValue > 0) {
                imageView.image = [UIImage imageNamed:@"zhong中"];
            }else{
                imageView.image = [UIImage imageNamed:@"weizhong未中"];
            }
            
            if (i < 4) {
                
                UIImageView *arrowView = [[UIImageView alloc] init];
                [backgroundView addSubview:arrowView];
                [arrowView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(imageView.mas_centerY).offset(0);
                    make.left.equalTo(imageView.mas_right).offset((magin - 13) / 2.0);
                    make.size.mas_equalTo(CGSizeMake(13, 9));
                }];
                arrowView.image = [UIImage imageNamed:@"jiantou箭头"];
            }
            
        }
        
        self.segTitle = [[ByCoreViewSegmentControl alloc] initWithFrame:CGRectMake(5, backgroundView.bottom + 2, SCREEN_WIDTH - 10, 45)];
        [header addSubview:self.segTitle];
        self.segTitle.sectionTitles = @[@"全部",@"足球",@"篮球",@"精华"];
        self.segTitle.backgroundColor = [UIColor whiteColor];
        self.segTitle.font = FONT(13);
        self.segTitle.scrollEnabled = YES;
        self.segTitle.textColor = [UIColor blackColor];
        self.segTitle.selectedTextColor = BY_THEME_COLOR;
        self.segTitle.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        self.segTitle.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        self.segTitle.selectionIndicatorHeight = 3;
        self.segTitle.segmentEdgeInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.segTitle.layer.cornerRadius = 5;
        self.segTitle.selectedSegmentIndex = self.type - 1;
        __weak typeof(self) weakSelf = self;
        [self.segTitle setIndexChangeBlock:^(NSInteger index) {
            weakSelf.type = index + 1;
            [weakSelf loadData];
        }];
       
        
        return header;
    }else{
        return [UIView new];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 140;
    }else{
        return 0.01;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.row];
    ByDocumentaryDetailVC *vc = [[ByDocumentaryDetailVC alloc] init];
    vc.netModel = netModel;
    [self by_normalPush:vc hasNavi:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
